const { Add, Update, QueryById, Query, Exec_Count,Execsql_Count } = require('../db/dbhelper');
var { init, format } = require('../models/message');


//新增
const messageAdd = function (doc) {
  return Add('hzz_messages', init(doc));
}

//修改
const messageUpdate = function (doc) {
  return Update('hzz_messages', format(doc));
}

//查询详情
const messageInfoById = function (id) {
  return QueryById('hzz_messages', id);
}

//列表
const messageList = function (doc) {
  return Query('hzz_messages', { recivecode: doc.pcode });
}

// 查询消息数量
const messageCount = async function(doc){
  try {
    if(!doc || !doc.pcode){
      return {
        code: 1,
        msg:'用户信息丢失，请刷新小程序'
      }
    }
    // let result={
    //   tasktodo_count: 0, // 待办数量
    //   access_count: 0, // 访客数量
    //   myfans_count: 0, // 收藏我的数量
    //   fanme_count: 0, // 我的收藏数量
    //   myuser_count: 0, // 我的用户数量
    //   lover_count: 0 // 情侣配对数量
    // };
    // 获取待办数量
    let tasktodo_count = await Execsql_Count(`select count(1) as total from hzz_tasktodos where pcode='${doc.pcode}' AND status= 0  AND length(gcode)=12`);
    // 获取访客数量
    let access_count = await Execsql_Count(`select count(1) as total from hzz_accessrecords where pcode='${doc.pcode}'  AND length(accesscode)=12 AND isread=0`);
    // 获取收藏我的数量
    let myfans_count = await Execsql_Count(`select count(1) as total from hzz_peoplefans where pcode='${doc.pcode}' AND state=1 AND length(fcode)=12 AND pisread=0`);
    // 获取我的收藏数量
    let fanme_count = await Execsql_Count(`select count(1) as total from hzz_peoplefans where fcode='${doc.pcode}' AND state=1 AND length(pcode)=12 AND fisread=0`);
    // 获取我的用户数量
    let myuser_count = await Execsql_Count(`select count(1) as total from hzz_peoples where invitcode='${doc.pcode}' AND confirm=1 AND ((online=1 AND isinviter=0) OR isinviter=1)  AND length(code)=12 AND isread=0`);
    // 获取情侣配对数量
    let lover_count = await Execsql_Count(`select count(1) as total from hzz_matchhistories  where ((visitcode='${doc.pcode}' AND visread =0)  OR (visitmatchcode='${doc.pcode}' AND misread =0)) AND length(visitcode)=12 AND length(visitmatchcode)=12 AND length(pcode)=12 AND length(matchcode)=12`);
    
    return {
      code:0,
      data: {
        tasktodo_count,access_count,myfans_count,fanme_count,myuser_count,lover_count
      },
      msg: '获取用户消息数量成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg:'程序异常，请联系客服'
    }
  }
}

module.exports = {
  messageAdd,
  messageUpdate,
  messageInfoById,
  messageList,
  messageCount
}